package com.dyh.quickdemo.demos.filedDef;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

@Setter@Getter
public class FieldAccessDefine<T,K> {



    String name;
//        Class<T> cls;
//        Class<K> valCls;
    Function<T,K> getter;
    BiConsumer<T,K> setter;

    /*没有这个无法使用lambda*/
    public static <T,K>  FieldAccessDefine<T,K> from(String name,Function<T,K> getter,BiConsumer<T,K> setter){
        FieldAccessDefine<T,K> result = new FieldAccessDefine<>();
        result.setName(name);
        result.setGetter(getter);
        result.setSetter(setter);
        return result;
        // return new FieldAccessDefine<>(name,getter,setter);
    }


    @Setter@Getter@AllArgsConstructor@NoArgsConstructor
    public   class Student{
        Long id;
        String name;
        List<Student> friend;
    }


    @Test
    public void t(){
//        FieldAccessDefine define = new
//                FieldAccessDefine("姓名",Student.class,String.class,Student::getName,Student::setName);

//        FieldAccessDefine.from("姓名",Student::getName,Student::setName);
//        FieldAccessDefine.from("编号",Student::getId,Student::setId);

        FieldAccessDefine[] defines ={FieldAccessDefine.from("姓名",Student::getName,Student::setName),
                FieldAccessDefine.from("编号",Student::getId,Student::setId)
        };

        Student s1 = new Student(null,"daw",null);
        Student s2 = new Student(1L,"daw1",null);
        String result = logChange(s1,s2,defines);
        System.out.println();
    }

    public static <T> String logChange(T old,T mono,FieldAccessDefine<T,?>[] defines){
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldAccessDefine<T, ?> define : defines) {
            Object oldVal = define.getter.apply(old);
            Object newVal = define.getter.apply(mono);
            if (newVal==null)
                continue;
            if (oldVal==null){
                stringBuilder.append("字段【").append(define.name).append("】")
                        .append("由旧值:【").append("null").append("】")
                        .append("变成:").append(newVal).append("】").append(";");
            }
            else {
                if (!oldVal.equals(newVal)){
                    stringBuilder.append("字段【").append(define.name).append("】")
                            .append("由旧值:【").append(oldVal).append("】")
                            .append("变成:").append(newVal).append("】").append(";");
                }
            }

        }
        return stringBuilder.toString();

    }
}
